package com.tanhua.dubbo.server.api.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.convert.Convert;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.ObjectUtil;
import com.alibaba.dubbo.config.annotation.Service;
import com.tanhua.dubbo.server.api.VisitorsApi;
import com.tanhua.dubbo.server.pojo.RecommendUser;
import com.tanhua.dubbo.server.pojo.Visitors;
import com.tanhua.dubbo.server.vo.PageInfo;
import org.bson.types.ObjectId;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.redis.core.RedisTemplate;



import java.util.List;
@Service(version = "1.0.0")
public class VisitorsApiImpl implements VisitorsApi {

    @Autowired
    private MongoTemplate mongoTemplate;

    private static final String VISITOR_REDIS_KEY = "VISITOR_USER";

    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    /**
     * 保存来访者信息
     * @param userId 我的id
     * @param visitorUserId 访客id
     * @param from 来源
     * @return
     */
    @Override
    public String saveVisitor(Long userId, Long visitorUserId, String from) {
        //校验
        if (!ObjectUtil.isAllNotEmpty(userId, visitorUserId, from)){
            return null;
        }
        //查询用户在今天是否已经记录，如果已经记录，则不在记录
        //当前时间:date = 2019-09-17 16:59:23  Date date = DateUtil.date();
        //当前日期字符串:today = 2019-09-17
        String today = DateUtil.today();
        long minDate = DateUtil.parseDateTime(today + " 00:00:00").getTime();
        long maxDate = DateUtil.parseDateTime(today + " 23:29:29").getTime();
        /*
        gt: greater than 大于
        gte: greater than or equal 大于等于
        lt: less than 小于
        lte: less than or equal 小于等于
         */
        Query query = Query.query(Criteria.where("userId").is(userId)
                .and("visitorUserId").is(visitorUserId)
                .andOperator(Criteria.where("date").gte(minDate),
                        Criteria.where("date").lte(maxDate)));


        long count = this.mongoTemplate.count(query, Visitors.class);
        if (count > 0){
            return null;
        }
        Visitors visitors = new Visitors();
        visitors.setDate(DateUtil.parseDate(today).getTime());
        visitors.setId(ObjectId.get());
        visitors.setUserId(userId);
        visitors.setVisitorUserId(visitorUserId);
        visitors.setFrom(from);

        this.mongoTemplate.save(visitors);
        //toHexString返回十进制的字符串
        return visitors.getId().toHexString();
    }

    /**
     * 查询最近访问信息
     * @param userId
     * @return
     */
    @Override
    public List<Visitors> queryMyVisitor(Long userId) {

        // 查询前5个访客数据，按照访问时间倒序排序
        // 如果用户已经查询过列表，记录查询时间，后续查询需要按照这个时间往后查询

        // 上一次查询列表的时间
        Long date = Convert.toLong(this.redisTemplate.opsForHash().get(VISITOR_REDIS_KEY, String.valueOf(userId)));

        Pageable pageRequest = PageRequest.of(0, 5, Sort.by(Sort.Order.desc("date")));
        Query query = Query.query(Criteria.where("userId").is(userId)).with(pageRequest);
        if (ObjectUtil.isNotEmpty(date)){
            query.addCriteria(Criteria.where("date").gte(date));
        }
        return queryList(userId, query);
    }

    private List<Visitors> queryList(Long userId, Query query) {
        List<Visitors> visitorsList = this.mongoTemplate.find(query, Visitors.class);
        if (CollUtil.isEmpty(visitorsList)){
            return null;
        }
        //查询每个来访用户的得分 推荐得分
        for (Visitors visitor : visitorsList) {
            /*
            userId; //推荐的用户id
            toUserId; //用户id
             */
            Query queryScore = Query.query(Criteria.where("toUserId").is(userId)
                    .and("userId").is(visitor.getVisitorUserId()));
            RecommendUser recommendUser = this.mongoTemplate.findOne(queryScore, RecommendUser.class);
            if (ObjectUtil.isNotEmpty(recommendUser)){
                visitor.setScore(recommendUser.getScore());
            }else {
                //默认得分
                visitor.setScore(90d);
            }
        }
        return visitorsList;
    }

    /**
     * 按照时间倒序排序，查询最近的访客信息
     *
     * @param userId
     * @param page
     * @param pageSize
     * @return
     */
    @Override
    public PageInfo<Visitors> topVisitor(Long userId, Integer page, Integer pageSize) {
        PageRequest pageRequest = PageRequest.of(page, pageSize, Sort.by(Sort.Order.desc("date")));

        Query query = Query.query(Criteria.where("userId").is(userId)).with(pageRequest);

        List<Visitors> visitorsList = this.queryList(userId, query);
        PageInfo<Visitors> pageInfo = new PageInfo<>();
        pageInfo.setPageNum(page);
        pageInfo.setPageSize(pageSize);
        pageInfo.setRecords(visitorsList);
        //由于高并发和高性能 所以用到Redis存储


        //记录当前的时间到redis中，在首页查询时，就可以在这个时间之后查询了
        String redisKey = VISITOR_REDIS_KEY;
        String hashKey = String.valueOf(userId);
        String value = String.valueOf(System.currentTimeMillis());
        this.redisTemplate.opsForHash().put(redisKey, hashKey, value);
        return pageInfo;
    }
}
